package controllers_admin

import (
	"github.com/kataras/iris"
	"github.com/kataras/iris/mvc"
	"manageCrontab/db"
	"manageCrontab/lib"
	"manageCrontab/models"
)

type LoginController struct {
}

func (c *LoginController) BeforeActivation(b mvc.BeforeActivation) {
	// httpMethod 参数一定要全大写
	b.Handle("GET", "/login", "Login")
	b.Handle("POST", "/dologin", "DoLogin").Name = "doLogin"
}

func (c *LoginController) Login() mvc.Result {
	return mvc.View{
		Name: "login.html",
	}
}

func (c *LoginController) DoLogin(ctx iris.Context) string {
	data := map[string]interface{}{}
	account := ctx.PostValue("username")
	password := ctx.PostValue("password")
	DB := db.GetDB()
	user := models.User{}
	DB.Model(models.User{}).Where("account = ?", account).First(&user)
	msg := "登录成功"
	data["User"] = user
	code := models.REQUEST_SUCCESS
	if user.Password != lib.Md5Str(password) {
		code = models.LOGIN_FIAL
		msg = "登录失败"
	}
	lib.SessionObj(ctx).Set("authenticated", true)
	lib.Session_.Start(ctx).Set("user", user)
	return lib.GetJsonResponse(code, data, msg)
}
